// 用户控制页面逻辑
document.addEventListener('DOMContentLoaded', () => {
    // 确保MQTT管理器已初始化
    if (!window.mqttManager) {
        window.mqttManager = new MQTTManager();
    }

    // 绑定事件
    bindEvents();
    
    // 初始化控制按钮
    initializeControlButtons();
    
    // 检查配置状态
    checkConfigStatus();
});

function bindEvents() {
    // 连接按钮
    const connectBtn = document.getElementById('connect-btn');
    if (connectBtn) {
        connectBtn.addEventListener('click', handleConnect);
    }

    // 断开连接按钮
    const disconnectBtn = document.getElementById('disconnect-btn');
    if (disconnectBtn) {
        disconnectBtn.addEventListener('click', handleDisconnect);
    }

    // 测试连接按钮
    const testBtn = document.getElementById('test-btn');
    if (testBtn) {
        testBtn.addEventListener('click', handleTestConnection);
    }

    // 控制按钮
    for (let i = 1; i <= 3; i++) {
        const btn = document.getElementById(`command-btn-${i}`);
        if (btn) {
            btn.addEventListener('click', () => handleCommand(i));
        }
    }

    // 清空日志按钮
    const clearLogBtn = document.getElementById('clear-log');
    if (clearLogBtn) {
        clearLogBtn.addEventListener('click', () => {
            window.mqttManager.clearLog();
        });
    }
}

function initializeControlButtons() {
    // 加载配置并更新按钮显示
    const config = window.mqttManager.config;
    
    if (config && config.commands) {
        config.commands.forEach((command, index) => {
            const btn = document.getElementById(`command-btn-${index + 1}`);
            if (btn) {
                const textSpan = btn.querySelector('.btn-text');
                if (textSpan) {
                    textSpan.textContent = command.buttonText || `指令${index + 1}`;
                }
            }
        });
    }
}

function checkConfigStatus() {
    const config = window.mqttManager.config;
    
    if (!config || !config.mqtt || !config.mqtt.brokerUrl) {
        window.mqttManager.addLog('警告：请先配置MQTT连接参数');
        return false;
    }

    // 检查指令配置
    let hasValidCommands = false;
    if (config.commands) {
        hasValidCommands = config.commands.some(cmd => cmd.topic && cmd.payload);
    }

    if (!hasValidCommands) {
        window.mqttManager.addLog('提示：请配置至少一个有效的控制指令');
    }

    return true;
}

async function handleConnect() {
    const connectBtn = document.getElementById('connect-btn');
    const originalText = connectBtn.textContent;
    
    try {
        connectBtn.disabled = true;
        connectBtn.textContent = '连接中...';
        
        await window.mqttManager.connect();
        
    } catch (error) {
        window.mqttManager.addLog(`连接失败: ${error.message}`);
        
        // 恢复按钮状态
        connectBtn.disabled = false;
        connectBtn.textContent = originalText;
    }
}

function handleDisconnect() {
    window.mqttManager.disconnect();
}

async function handleTestConnection() {
    const testBtn = document.getElementById('test-btn');
    const originalText = testBtn.textContent;
    
    try {
        testBtn.disabled = true;
        testBtn.textContent = '测试中...';
        
        const result = await window.mqttManager.testConnection();
        
        if (result) {
            window.mqttManager.addLog('✓ 连接测试成功，可以正常连接');
        } else {
            window.mqttManager.addLog('✗ 连接测试失败，请检查配置');
        }
        
    } catch (error) {
        window.mqttManager.addLog(`测试连接异常: ${error.message}`);
    } finally {
        testBtn.disabled = false;
        testBtn.textContent = originalText;
    }
}

async function handleCommand(commandIndex) {
    if (!window.mqttManager.isConnected) {
        window.mqttManager.addLog('错误：MQTT未连接');
        return;
    }

    const config = window.mqttManager.getCommandConfig(commandIndex);
    if (!config || !config.topic || !config.payload) {
        window.mqttManager.addLog(`错误：指令${commandIndex}未配置`);
        return;
    }

    const btn = document.getElementById(`command-btn-${commandIndex}`);
    const originalText = btn.querySelector('.btn-text').textContent;
    
    try {
        // 按钮反馈
        btn.disabled = true;
        btn.querySelector('.btn-text').textContent = '发送中...';
        
        // 发送MQTT消息（支持QoS配置）
        const qos = config.qos || 0;
        await window.mqttManager.publish(config.topic, config.payload, qos);
        
        // 恢复按钮状态
        setTimeout(() => {
            btn.disabled = false;
            btn.querySelector('.btn-text').textContent = originalText;
        }, 1000);
        
    } catch (error) {
        window.mqttManager.addLog(`发送失败: ${error.message}`);
        
        // 恢复按钮状态
        btn.disabled = false;
        btn.querySelector('.btn-text').textContent = originalText;
    }
}

// 页面可见性变化处理
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        // 页面隐藏时，如果连接着则断开（可选）
        // window.mqttManager.disconnect();
    }
});

// 页面卸载前清理
window.addEventListener('beforeunload', () => {
    if (window.mqttManager && window.mqttManager.isConnected) {
        window.mqttManager.disconnect();
    }
});

// 导出函数供全局使用
window.handleConnect = handleConnect;
window.handleDisconnect = handleDisconnect;
window.handleCommand = handleCommand;